/**
 * Created by Sage on 2016/6/23.
 */

var delay_time=0;
var p1=[];
var p2=[];
var elem;
var time=0;
var move_time;

function touch_start(event,$this){

}
//触摸移动
function touch_move(event,$this){

    var left=event.touches[0].clientX-$this.width()/2;
    var top=event.touches[0].clientY-$this.height()/2;

    if(left<$this.width()/2){
        left=0;
    }
    if(top<$this.height()/2){
        top=0;
    }


    if(left>window.innerWidth -$this.width()){
        left=window.innerWidth-$this.width();
    }
    if(top>window.innerHeight -$this.height()){
        top=window.innerHeight -$this.height();
    }
    $this.css('left',left+'px');
    $this.css('top',top+'px');
    delay_time++;
    if(delay_time>3){
        var x=event.touches[0].clientX;
        var y=event.touches[0].clientY;
        p1=p2;
        p2=[x,y];
        delay_time=0;
    }
    move_time=new Date().getTime();
}

//触摸离屏
function touch_end(event,$this){
    elem=$this;
    elem.left=$this.css('left') ;
    elem.top=$this.css('top');
    var now=new Date().getTime();
    var q=now-move_time;
//        log(q);
    if(q<=80 && Math.abs(p1[0]-p2[0])>4 && Math.abs(p1[1]-p2[1])>4){
        time=80;
        setTimeout("touch_animation('"+time+"')",10);
    }
}

function touch_animation($time){
    $time=parseInt($time);
    var $this=elem;
    var px=p2[0]-p1[0]+parseInt($this.css('left'));
    var py=p2[1]-p1[1]+parseInt($this.css('top'));

    if(px<0 || px>window.innerWidth-$this.width()){
        var t=p2[0];
        p2[0]=p1[0];
        p1[0]=t;
    }

    if(py<0 || py>window.innerHeight-$this.height()){
        var t=p2[1];
        p2[1]=p1[1];
        p1[1]=t;
    }
    var y=$time/time;
    var px=(p2[0]-p1[0])*y+parseInt($this.css('left'));
    var py=(p2[1]-p1[1])*y+parseInt($this.css('top'));

    $this.css('left',px);
    $this.css('top',py);
    $time-=1;
    if($time>0){
        setTimeout("touch_animation('"+$time+"')",10);
    }
}